﻿using System.Linq;

namespace Collatz
{
    /// <summary>
    /// 表示普通解算方法的类
    /// </summary>
    public class PlainSolver : Solver
    {
        /// <summary>
        /// 用指定的最大数值创建一个实例
        /// </summary>
        /// <param name="start">最大数值，从此数值开始向递减方向解算</param>
        /// <exception cref="ArgumentOutOfRangeException">当<paramref name="start"/>不是正整数时引发</exception>
        public PlainSolver(int start)
            : base(start)
        {

        }

        /// <summary>
        /// 从<see cref="Start"/>开始依次递减，解算最长序列
        /// </summary>
        /// <returns>最长序列的开始数值</returns>
        public override int Solve()
        {
            return (int)Enumerable
                .Range(1, _start)
                .Reverse()
                .Select(number => new CollatzSerial(number))
                .Aggregate(new { Serial = (CollatzSerial)null, Count = 0L }, (max, serial) =>
                {
                    var count = serial.LongCount();
                    return count > max.Count ? new { Serial = serial, Count = count } : max;
                }).Serial.Start;
        }
    }
}
